<template>
	<el-dialog
		:title="form.id ? $t('common.editBtn') : $t('common.addBtn')"
		v-model="visible"
		:close-on-click-modal="false"
		@close="modalClose"
		draggable
	>
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="120px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item prop="shopId" :label="$t('Prod.shopId')">
						<ShopSelect v-model="form.shopId"></ShopSelect>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="name" :label="$t('Prod.name')">
						<el-input v-model="form.name" :placeholder="$t('Prod.inputNameTip')" clearable show-word-limit :maxlength="128" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="brief" :label="$t('Prod.subTitle')">
						<el-input v-model="form.brief" :placeholder="$t('Prod.inputSubTitleTip')" clearable show-word-limit :maxlength="255" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="categoryId" :label="$t('Prod.categoryId')">
						<SelectTree v-model="form.categoryId"></SelectTree>

						<!-- <el-select v-model="form.categoryId" :placeholder="$t('Prod.inputCategoryIdTip')" clearable filterable>
              <el-option :value="item.id" :label="item.id" v-for="item in prodCategoryIdOption"
                :key="item!.id"></el-option>

            </el-select> -->
					</el-form-item>
				</el-col>

				<!-- <el-col :span="12" class="mb20">
          <el-form-item prop="categoryPath" :label="$t('Prod.categoryPath')">
            <el-input v-model="form.categoryPath" :placeholder="$t('Prod.inputCategoryPathTip')" clearable show-word-limit
              :maxlength="255" />
          </el-form-item>
        </el-col> -->

				<el-col :span="12" class="mb20">
					<el-form-item prop="originAmount" :label="$t('Prod.originAmount')">
						<el-input-number
							v-model="form.originAmount"
							:placeholder="$t('Prod.inputOriginAmountTip')"
							clearable
							:min="1"
							:max="1000"
						></el-input-number>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="amount" :label="$t('Prod.amount')">
						<el-input-number v-model="form.amount" :placeholder="$t('Prod.inputAmountTip')" clearable :min="1" :max="1000"></el-input-number>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="sn" :label="$t('Prod.sn')">
						<el-input v-model="form.sn" :placeholder="$t('Prod.inputSnTip')" clearable show-word-limit :maxlength="50" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="model" :label="$t('Prod.model')">
						<el-input v-model="form.model" :placeholder="$t('Prod.inputModelTip')" clearable show-word-limit :maxlength="50" />
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item prop="pic" :label="$t('Prod.prodPic')">
						<upload-img v-model:image-url="form.pic" :requestData="{isProdPic:true}"></upload-img>
						<!-- <el-button v-if="form!.banner!.length < 5" @click="addUploadImg(form.banner)" type="primary" icon="Plus" /> -->
					</el-form-item>
				</el-col>
				<el-col :span="12" class="mb20">
					<el-form-item prop="banner" :label="$t('Prod.banner')">

						<Upload v-model:imgList="form.banner"  :limit="5"  :multiple="true"> </Upload>

						<!-- <upload-img @delete="delUpload(form.banner, index)" v-for="item, index in form.banner" :key="index"
              v-model:image-url="item.url"></upload-img>
            <el-button v-if="form!.banner!.length < 5" @click="addUploadImg(form.banner)" type="primary" icon="Plus" /> -->
					</el-form-item>
				</el-col>
<!--      缩略图-->
<!--				<el-col :span="12" class="mb20">-->
<!--					<el-form-item prop="thumbnail" :label="$t('Prod.thumbnail')">-->


<!--						<Upload v-model:imgList="form.thumbnail"-->
<!--               :limit="5"  :multiple="true"  > </Upload>-->

<!--					</el-form-item>-->
<!--				</el-col>-->

				<el-col :span="12" class="mb20">
  <el-form-item prop="descPic" :label="$t('Prod.descPic')">
						<Upload :limit="5" v-model:imgList="form.descPic" :multiple="true"> </Upload>

					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="desc" :label="$t('Prod.desc')">
						<el-input v-model="form.desc" :placeholder="$t('Prod.inputDescTip')" clearable show-word-limit :maxlength="65535" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="saleNum" :label="$t('Prod.saleNum')">
						<el-input-number v-model="form.saleNum" :placeholder="$t('Prod.inputSaleNumTip')" clearable :min="1" :max="1000"></el-input-number>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="totalStocks" :label="$t('Prod.totalStocks')">
						<el-input-number
							v-model="form.totalStocks"
							:placeholder="$t('Prod.inputTotalStocksTip')"
							clearable
							:min="1"
							:max="1000"
						></el-input-number>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="isSale" :label="$t('Prod.isSale')">
						<el-switch :active-value="true" :inactive-value="false" v-model="form.isSale" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="isCustomizable" :label="$t('Prod.isCustomizable')">
						<el-switch :active-value="true" :inactive-value="false" v-model="form.isCustomizable" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="isRecommend" :label="$t('Prod.isRecommend')">
						<el-switch :active-value="true" :inactive-value="false" v-model="form.isRecommend" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item prop="isHot" :label="$t('Prod.isHot')">
						<el-switch :active-value="true" :inactive-value="false" v-model="form.isHot" />
					</el-form-item>
				</el-col>

				<!-- <el-col :span="12" class="mb20">
          <el-form-item prop="deliveryType" :label="$t('Prod.deliveryType')">
            <el-input-number v-model="form.deliveryType" :placeholder="$t('Prod.inputDeliveryTypeTip')" clearable :min="1"
              :max="1000"></el-input-number>
          </el-form-item>
        </el-col> -->

				<!-- <el-col :span="12" class="mb20">
          <el-form-item prop="deliveryAddress" :label="$t('Prod.deliveryAddress')">
            <el-input v-model="form.deliveryAddress" :placeholder="$t('Prod.inputDeliveryAddressTip')" clearable
              show-word-limit :maxlength="255" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item prop="deliveryCycle" :label="$t('Prod.deliveryCycle')">
            <el-input v-model="form.deliveryCycle" :placeholder="$t('Prod.inputDeliveryCycleTip')" clearable
              show-word-limit />
          </el-form-item>
        </el-col> -->

				<!-- <el-col :span="12" class="mb20">
          <el-form-item prop="deliveryTemplateId" :label="$t('Prod.deliveryTemplateId')">
            <el-input v-model="form.deliveryTemplateId" :placeholder="$t('Prod.inputDeliveryTemplateIdTip')" clearable
              show-word-limit />
          </el-form-item>
        </el-col> -->

				<!-- <el-col :span="12" class="mb20">
          <el-form-item prop="commissionType" :label="$t('Prod.commissionType')">
            <el-input v-model="form.commissionType" :placeholder="$t('Prod.inputCommissionTypeTip')" clearable
              show-word-limit />
          </el-form-item>
        </el-col> -->

				<!-- <el-col :span="12" class="mb20">
          <el-form-item prop="commissionValue" :label="$t('Prod.commissionValue')">
            <el-input v-model="form.commissionValue" :placeholder="$t('Prod.inputCommissionValueTip')" clearable
              show-word-limit />
          </el-form-item>
        </el-col> -->

				<el-col :span="12" class="mb20">
					<el-form-item prop="sort" :label="$t('Prod.sort')">
						<el-input-number v-model="form.sort" :placeholder="$t('Prod.inputSortTip')" clearable :min="1" :max="1000"></el-input-number>
					</el-form-item>
				</el-col>

				<!-- <el-col :span="12" class="mb20">
          <el-form-item prop="source" :label="$t('Prod.source')">
            <el-input v-model="form.source" :placeholder="$t('Prod.inputSourceTip')" clearable show-word-limit
              :maxlength="255" />
          </el-form-item>
        </el-col> -->

				<!-- <el-col :span="12" class="mb20">
          <el-form-item prop="sourceUrl" :label="$t('Prod.sourceUrl')">
            <el-input v-model="form.sourceUrl" :placeholder="$t('Prod.inputSourceUrlTip')" clearable show-word-limit
              :maxlength="255" />
          </el-form-item>
        </el-col> -->

				<el-col :span="24">
					<div class="specification">
						<div class="specification-header">
							<span> {{ $t('Prod.attributeFilling') }} </span>
							<el-button type="primary" @click="addSpec" :disabled="prodSpecList.length >= 5">{{ $t('Prod.addAttribute') }}</el-button>
						</div>

						<div class="specification-body" v-for="(item, index) in prodSpecList" :key="index">
							<div class="body-item">
								<span class="label-item">{{ $t('Prod.attributeName') }}</span>

								<el-select
									class="selectPC"
									@blur="productSelect($event, item)"
									v-model="item.specAtt"
									@change="changeProdPropFn($event, item)"
									:placeholder="$t('Prod.selectProdAttribute')"
									default-first-option
									clearable
									filterable
									allow-create
								>
									<el-option v-for="item in prodPropList" :key="item.propId" :label="item.propName" :value="item.propName" />
								</el-select>

								<el-button class="puls-button" type="danger" icon="Delete" @click="delProdSpecList(prodSpecList, index)"></el-button>
							</div>

							<div class="body-item">
								<span class="label-item">{{ $t('Prod.attributeValue') }}</span>

								<div class="child-sel">
									<div :key="rIndex" v-for="(r, rIndex) in item.specValueList" class="child-sel-box">
										<el-select
											class="selectPC"
											@blur="productSelectVal($event, r, item)"
											v-model="r.specValue"
											:placeholder="$t('Prod.selectAttributeValue')"
											clearable
											filterable
											allow-create
											default-first-option
											@change="changeSpecVal($event, item, rIndex, index)"
										>
											<el-option v-for="cItem in item.specValueSelectList" :key="cItem.valueId" :label="cItem.valueName" :value="cItem.valueName" />
										</el-select>

										<el-icon
											@click="delChildSel(item.specValueList, rIndex)"
											v-if="item.specValueList.length > 1 && item.specValueList.length - 1 !== rIndex"
										>
											<Delete />
										</el-icon>
									</div>
								</div>
								<!-- <el-button class="puls-button" type="primary" :disabled="item.specValueList.length >= 5" icon="Plus"
                  @click="addSpecValuelist(item)"></el-button> -->
							</div>
						</div>
					</div>
				</el-col>
				<el-col :span="24">
					<FormTable :isCustomizable="form.isCustomizable" ref="FormTableREF" v-model:tableData="newProdSpecListTable"></FormTable>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">{{ $t('common.confirmButtonText') }}</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="ProdDialog">
import { useMessage } from '/@/hooks/message';
import { addObj, getObj, putObj } from '/@/api/bizs/Prod';
import { getList, getPropValuePage } from '/@/api/bizs/ProdProp';
import { SkuList, SubmitProd } from './types/Prod';
import FormTable from './components/formTable.vue';
import Upload from '/@/components/biz/uploadImg.vue';
// 定义i18n
import { useI18n } from 'vue-i18n';
// 引入组件
const ShopSelect = defineAsyncComponent(() => import('/@/components/ShopSelect/index.vue'));
const SelectTree = defineAsyncComponent(() => import('/@/components/biz/selectTreeCom.vue'));

const emit = defineEmits(['refresh']);

const { t } = useI18n();


defineProps(['shopIdOption', 'prodCategoryIdOption']);

interface ProdPropList {
	createBy: string;
	createTime: string;
	updateBy: string;
	updateTime: string;
	search?: any;
	rangeTime?: any;
	propId: string;
	propName: string;
	rule: number;
	shopId?: any;
}

interface ProdSpecList {
	specAtt: string;
	specValueList: SpecValueList[];
	specValueSelectList?: any[];
}

interface SpecValueList {
	specValue: string;
}

// const fileList = ref<ImgItem[]>([{ url: "" }])
const getFileListFn = (file: ImgItem, str: formKeys) => {
	(form[str] as ImgItem[]).push(file);
};

// 接收分类id
const prodSpecList = ref<ProdSpecList[]>([]);

type CurrentSet = {
	[key: string]: string;
};

function combineSpecs(input: ProdSpecList[], index: number, currentSet: CurrentSet, results: any) {
	if (index === input.length || input[index].specValueList.length == 0) {
		let values = Object.values(currentSet);
		let newCurrentSet: CurrentSet = {};

		for (let i = 1; i <= values.length / 2; i++) {
			if (currentSet['key' + i] && currentSet['value' + i]) {
				newCurrentSet['key' + i] = currentSet['key' + i];
				newCurrentSet['value' + i] = currentSet['value' + i];
			}
		}
		results.push(newCurrentSet);
	} else {
		for (let value of input[index].specValueList) {
			let newSet = { ...currentSet, ['key' + (index + 1)]: input[index].specAtt, ['value' + (index + 1)]: value.specValue };
			combineSpecs(input, index + 1, newSet, results);
		}
	}
	return results;
}

const newProdSpecListTable = ref([]);

const FormTableREF = ref();

const productSelect = (e: any, item: any) => {
	if (e.target.value) {
		item.specAtt = e.target.value;
		changeProdPropFn(e.target.value, item);
	}
};

const productSelectVal = (e: any, r: { specValue: string }, item: ProdSpecList) => {
	if (e.target.value) {
		r.specValue = e.target.value;
		let flag = item.specValueList.every((el: any) => el.specValue);
		if (e.target.value && flag) {
			item.specValueList.push({
				specValue: '',
			});
		}
	}
};

// 切换属性值
const changeSelectValue = () => {
	newProdSpecListTable.value = combineSpecs(prodSpecList.value, 0, {}, [])
		.map((el: any) => {
			const filteredObj: any = {};
			for (let key in el) {
				if (key && el[key]) {
					filteredObj[key] = el[key];
				}
			}
			return filteredObj;
		})
		.filter((el: any) => Object.values(el).length && Object.values(el).length % 2 == 0);
	// 处理formTabel组件数组
	// FormTableREF.value.reduceTableDataForm()

	if (newProdSpecListTable.value[0]) {
		let PropItemObjNum = Object.values(newProdSpecListTable.value[0]).length;
		newProdSpecListTable.value = newProdSpecListTable.value.filter((el) => Object.values(el).length == PropItemObjNum);
	}

	FormTableREF.value.tableDataForm = newProdSpecListTable.value.map((el: any, index: number) => {
		return {
			...el,
			amount: FormTableREF.value.tableDataForm[index] ? FormTableREF.value.tableDataForm[index].amount : 0,
			actualStocks: FormTableREF.value.tableDataForm[index] ? FormTableREF.value.tableDataForm[index].actualStocks : 0,
			buyMinLimit: FormTableREF.value.tableDataForm[index] ? FormTableREF.value.tableDataForm[index].buyMinLimit : 0,
			buyMaxLimit: FormTableREF.value.tableDataForm[index] ? FormTableREF.value.tableDataForm[index].buyMaxLimit : 0,
			properties: FormTableREF.value.tableDataForm[index] ? FormTableREF.value.tableDataForm[index].properties : 0,
			pic: FormTableREF.value.tableDataForm[index] ? FormTableREF.value.tableDataForm[index].pic : '',
			originAmount: FormTableREF.value.tableDataForm[index] ? FormTableREF.value.tableDataForm[index].originAmount : '',
		};
	});
};

const promiseList = ref<Promise<any>[]>([]);

const sukReList = (input: SkuList[]) => {
	const output: ProdSpecList[] = [];
	input.forEach((item: SkuList) => {
		const properties = item.properties.split(';').map((property: string) => property.split(':'));
		properties.forEach(([attribute, value]: string[]) => {
			const existingAttribute = output.find((obj) => obj.specAtt === attribute);
			if (existingAttribute) {
				const existingValue = existingAttribute.specValueList.find((v: SpecValueList) => v.specValue === value);
				if (!existingValue) {
					existingAttribute.specValueList.push({ specValue: value });
				}
			} else {
				promiseList.value.push(getSpecListFn(attribute));
				output.push({
					specAtt: attribute,
					specValueList: [{ specValue: value }],
				});
			}
		});
	});

	output.forEach((item) => {
		item.specValueList.push({
			specValue: '',
		});
	});

	return output;
};

// 监听属性
watch(
	() => prodSpecList.value.map((el) => el.specValueList),
	() => {
		nextTick(() => {
			changeSelectValue();
		});
	},
	{
		deep: true,
	}
);

type ImgItem = { url: string };

type formKeys = keyof SubmitProd;

const delImage = (image: string, str: formKeys) => {
	let index = (form[str] as ImgItem[]).findIndex((el: ImgItem) => el.url == image);
	if (index !== -1) {
		(form[str] as ImgItem[]).splice(index, 1);
	}
};

// 删除规格
const delProdSpecList = (list: ProdSpecList[], index: number) => {
	list.splice(index, 1);
};

const modalClose = () => {
	nextTick(() => {
		prodSpecList.value = [];
	});
};

//添加规格
const addSpec = () => {
	prodSpecList.value.push({
		specAtt: '',
		specValueList: [
			{
				specValue: '',
			},
		],
		specValueSelectList: [],
	});
};

const prodPropList = ref<ProdPropList[]>([]);
const getProdPropListFn = async () => {
	let res = await getList({});
	prodPropList.value = res.data;
};
getProdPropListFn();

// 切换规格名
const changeProdPropFn = async (e: string, item: ProdSpecList) => {
	if (e) {
		item.specValueSelectList = await getSpecListFn(e);
		let list = item.specValueSelectList;

		item.specValueList = list!
			.map((el: { valueName: string }) => {
				return {
					specValue: el.valueName,
				};
			})
			.filter((el: { specValue: string }, index: number) => el.specValue && index < 5);
	} else {
		item.specValueList = [];
	}

	item.specValueList.push({
		specValue: '',
	});
};

const changeSpecVal = (e: string, item: ProdSpecList, index: number, pIndex: number) => {
	if (!e) {
		item.specValueList.splice(index, 1);
	}

	if (item.specValueList.length == 1 && !item.specValueList[0].specValue) {
		prodSpecList.value.splice(pIndex, 1);
	}

	let flag = item.specValueList.every((el: SpecValueList) => el.specValue);
	if (e && flag) {
		item.specValueList.push({
			specValue: '',
		});
	}
};

// 添加规格值
const addSpecValuelist = (item: any) => {
	if (!item.specValueList.every((row: any) => row.specValue)) return;
	item.specValueList.push({
		specValue: '',
	});
};

const delChildSel = (list: SpecValueList[], index: number) => {
	if (list.length == 1) return;
	list.splice(index, 1);
};

// 获取规格值列表
const getSpecListFn = async (e: string) => {
	let res = await getPropValuePage({
		propName: e,
		size: 10,
		current: 1,
	});
	return res.data.records;
};

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const dataFormRef = ref();

// 提交表单数据
const form = reactive<SubmitProd>({
	id: '',
	shopId: '', // 店铺
	name: '',
	brief: '',
	categoryId: '',
	categoryPath: '',
	originAmount: 0,
	amount: 0,
	sn: '',
	model: '',
	banner: [],
	thumbnail: [],
	descPic: [], // 详情描述图
	desc: '',
	saleNum: 0,
	totalStocks: 0,
	isSale: false,
	isCustomizable: false,
	isRecommend: false,
	isHot: false,
	deliveryType: 0,
	deliveryAddress: '',
	deliveryCycle: '',
	deliveryTemplateId: '',
	commissionType: '',
	commissionValue: '',
	sort: 0,
	source: '',
	sourceUrl: '',
	pic: '',
});

// 定义校验规则
// import { rule } from '/@/utils/validate';
const dataRules = ref({
	shopId: [{ required: true, message: t('Prod.inputShopIdTip'), trigger: 'blur' }],
	name: [{ required: true, message: t('Prod.inputNameTip'), trigger: 'blur' }],
	brief: [{ required: true, message: t('Prod.inputSubTitleTip'), trigger: 'blur' }],
	categoryId: [{ required: true, message: t('Prod.inputCategoryIdTip'), trigger: 'blur' }],
	categoryPath: [{ required: false, message: t('Prod.inputCategoryPathTip'), trigger: 'blur' }],
	originAmount: [{ required: true, message: t('Prod.inputOriginAmountTip'), trigger: 'blur' }],
	amount: [{ required: true, message: t('Prod.inputAmountTip'), trigger: 'blur' }],
	sn: [{ required: false, message: t('Prod.inputSnTip'), trigger: 'blur' }],
	model: [{ required: false, message: t('Prod.inputModelTip'), trigger: 'blur' }],
	banner: [{ required: false, message: t('Prod.inputBannerTip'), trigger: 'blur' }],
	thumbnail: [{ required: false, message: t('Prod.inputThumbnailTip'), trigger: 'blur' }],
	desc: [{ required: false, message: t('Prod.inputDescTip'), trigger: 'blur' }],
	saleNum: [{ required: false, message: t('Prod.inputSaleNumTip'), trigger: 'blur' }],
	totalStocks: [{ required: false, message: t('Prod.inputTotalStocksTip'), trigger: 'blur' }],
	isSale: [{ required: false, message: t('Prod.inputIsSaleTip'), trigger: 'blur' }],
	isCustomizable: [{ required: false, message: t('Prod.inputIsCustomizableTip'), trigger: 'blur' }],
	isRecommend: [{ required: false, message: t('Prod.inputIsRecommendTip'), trigger: 'blur' }],
	isHot: [{ required: false, message: t('Prod.inputIsHotTip'), trigger: 'blur' }],
	deliveryType: [{ required: false, message: t('Prod.inputDeliveryTypeTip'), trigger: 'blur' }],
	deliveryAddress: [{ required: false, message: t('Prod.inputDeliveryAddressTip'), trigger: 'blur' }],
	deliveryCycle: [{ required: false, message: t('Prod.inputDeliveryCycleTip'), trigger: 'blur' }],
	deliveryTemplateId: [{ required: false, message: t('Prod.inputDeliveryTemplateIdTip'), trigger: 'blur' }],
	commissionType: [{ required: false, message: t('Prod.inputCommissionTypeTip'), trigger: 'blur' }],
	commissionValue: [{ required: false, message: t('Prod.inputCommissionValueTip'), trigger: 'blur' }],
	sort: [{ required: false, message: t('Prod.inputSortTip'), trigger: 'blur' }],
	source: [{ required: false, message: t('Prod.inputSourceTip'), trigger: 'blur' }],
	sourceUrl: [{ required: false, message: t('Prod.inputSourceUrlTip'), trigger: 'blur' }],
});

// 打开弹窗
const openDialog = (id: string) => {
	visible.value = true;
	form.id = '';

	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
		FormTableREF.value.customData = {
			amount: 0,
			actualStocks: 1,
			buyMinLimit: 1,
			pic: 'https://oss.king-of-panda.com/biz/custom.png',
			skuName: 'Custom',
		};
	});

	// 获取信息
	if (id) {
		form.id = id;
		initFormData(id);
	}
};

// 初始化表单
const initFormData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj(id)
		.then((res: any) => {
			Object.assign(form, res.data, {
				banner: addUrlArrFn(res.data.banner),
				descPic: addUrlArrFn(res.data.descPic),
				thumbnail: addUrlArrFn(res.data.thumbnail),
        saleNum:Number(res.data.saleNum)
			});

			if (form.isCustomizable) {
				console.log(form.skuList, 'form.skuList1');
				let { amount, actualStocks, buyMinLimit, pic, skuName } = form.skuList?.pop();
				console.log(form.skuList, 'form.skuList2');
				FormTableREF.value.customData = {
					amount,
					actualStocks,
					buyMinLimit,
					pic,
					skuName,
				};
			}
		})
		.finally(() => {


			loading.value = false;
			// 编辑回显表格
			prodSpecList.value = sukReList(form.skuList as SkuList[]);
			FormTableREF.value.tableDataForm = form.skuList!.map((el) => {
				let { amount, actualStocks, buyMinLimit, buyMaxLimit, properties, pic, originAmount } = el;
				return {
					amount, // 价格
					actualStocks, // 实际库存
					buyMinLimit, // 最小购买数
					buyMaxLimit, // 最大购买数
					properties, //  销售属性组合字符串 格式是p1:v1;p2:v2
					pic, // 图片
					originAmount, // 原价
				};
			});

			Promise.all(promiseList.value).then((res) => {
				prodSpecList.value = prodSpecList.value.map((el: ProdSpecList, index: number) => {
					return {
						...el,
						specValueSelectList: res[index],
					};
				});
			});
		});
};

const addUrlArrFn = (arr: string[]) => {
	return arr.map((el: string) => {
		return {
			url: el,
		};
	});
};

// 提交表单
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	let submitForm = formProcessing(form);
	try {
		loading.value = true;
		const {ok, msg} = form.id ? await putObj(submitForm) : await addObj(submitForm);
    if (ok) {
      useMessage().success(form.id ? t('common.editSuccessText') : t('common.addSuccessText'));
      visible.value = false;
      emit('refresh');
    } else {
      useMessage().error(msg)
    }
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

const processSkuName = (obj: SkuList) => {
	let result = '';
	Object.keys(obj).forEach((key: unknown, index: number) => {
		if (index < Object.keys(obj).length - 1) {
			result += `${obj[key as keyof SkuList]}`;
			if (index % 2 === 0) {
				// result += ",";
			} else {
				result += ' ';
			}
		} else {
			result += `${obj[key as keyof SkuList]}`;
		}
	});
	return result;
};

const processStr = (obj: any) => {
	let result = '';
	Object.keys(obj).forEach((key, index) => {
		if (index < Object.keys(obj).length - 1) {
			result += `${obj[key]}`;
			if (index % 2 === 0) {
				result += ':';
			} else {
				result += ';';
			}
		} else {
			result += `${obj[key]}`;
		}
	});
	return result;
};

// 表单处理

const formProcessing = (form: SubmitProd) => {
	let skuList = newProdSpecListTable.value.map((el: any, index: number) => {
		return {
			createBy: '',
			createTime: '',
			updateBy: '',
			updateTime: '',
			search: '',
			rangeTime: [],
			id: '',
			prodId: 0,
			isSale: 1,
			skuName: processSkuName(el),
			prodName: '',
			desc: '',
			originAmount: 0,
			virtualStock: 0,

			sellCount: 0,
			weight: 0,
			volume: 0,
			buyMaxLimit: 0,
			sort: 0,
			properties: processStr(el),
			actualStocks: FormTableREF.value.tableDataForm[index].actualStocks,
			amount: FormTableREF.value.tableDataForm[index].amount,
			buyMinLimit: FormTableREF.value.tableDataForm[index].buyMinLimit,
			pic: FormTableREF.value.tableDataForm[index].pic,
		};
	});

	if (form.isCustomizable) {
		skuList.push({
			createBy: '',
			createTime: '',
			updateBy: '',
			updateTime: '',
			search: '',
			rangeTime: [],
			id: '',
			prodId: 0,
			isSale: 1,
			prodName: '',
			desc: '',
			originAmount: 0,
			virtualStock: 0,
			sellCount: 0,
			weight: 0,
			volume: 0,
			buyMaxLimit: 0,
			sort: 0,
			properties: FormTableREF.value.customData.skuName,
			...FormTableREF.value.customData,
		});
	}

	let obj = {
		...form,
		banner: proceArr(form.banner as { url: string }[]),
		descPic: proceArr(form.descPic as { url: string }[]),
		// thumbnail: proceArr(form.thumbnail as { url: string }[]),
		skuList,
	};

	return obj;
};

const proceArr = (arr: { url: string }[]): string[] => {
	let newArr = arr.map((el: { url: string }) => el.url);
	return newArr;
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style lang="scss" scoped>
.selectPC {
	width: 200px !important;
}

.prod-prop-box {
	display: flex;
	gap: 10px;
}

.specification {
	display: flex;
	flex-direction: column;
	gap: 10px;

	.specification-header {
		background-color: #f8f8f8;
		align-items: center;
		display: flex;
		padding: 10px;
		justify-content: space-between;
	}

	.specification-body {
		display: flex;
		flex-direction: column;
		border-bottom: 1px #409eff solid;

		.body-item {
			display: flex;
			align-items: center;
			padding: 10px;

			.child-sel {
				display: flex;
				flex-wrap: wrap;
				gap: 10px;
				width: 91%;

				.child-sel-box {
					display: flex;
					align-items: center;
					gap: 10px;
				}
			}

			.label-item {
				margin-right: 10px;
			}

			&:nth-child(2n) {
				background-color: #f8f8f8;
			}
		}

		.puls-button {
			margin-left: auto;
		}
	}
}
</style>
